<?php

declare(strict_types=1);

namespace App\Server;

use GuzzleHttp\Client;
use Hyperf\Utils\Coroutine;
use GuzzleHttp\HandlerStack;
use Hyperf\Guzzle\PoolHandler;
use Hyperf\Guzzle\RetryMiddleware;

/**
 * @Description 网络请求类
 * @author wuxian
 * @since 2020-04-15
 */
class GuzzleNetwork
{
    protected $client;

    /**
     * @param array $config  基本配置
     * @return null
     */
    public function __construct($config = [])
    {
        $handler = null;
        if (Coroutine::inCoroutine()) {
            $handler = make(PoolHandler::class, [
                'option' => [
                    'max_connections' => 15,
                ],
            ]);
        }
        $stack = HandlerStack::create($handler);
        $config['handler'] = $stack;
        $this->client = make(Client::class, [
            'config' => $config,
        ]);
    }

    /**
     * @param string $url  get请求的地址
     * @return array
     */
    public function get($url = '')
    {
        try {
            $content = $this->client->get($url)->getBody()->getContents();
            return ['errorCode'=>0, 'data'=>$content]; 
        } catch (\Throwable $t) {
            return ['errorCode' => 500, 'data' => $t->getMessage()];
        }
    }
    /**
     * @param string $url  post请求的地址
     * @param array $data  post请求数据
     * @return array
     */
    public function post($url = '', $data = [])
    {
        $param['form_params'] = $data;
        try {
            $content = $this->client->post($url, $param)->getBody()->getContents();
            return ['errorCode' => 0, 'data' => $content];
        } catch (\Throwable $t) {
            return ['errorCode' => 500, 'data' => $t->getMessage()];
        }
    }
}
